<script setup>
  import {
    onMounted,
    ref
  } from 'vue';
  import {
    useRoute
  } from 'vue-router'
  import {
    baseUrl,
    appid,
  } from "@/config/index.js"

  import {
    loginApi,
    getInfoApi,
  } from "@/assets/api/other/login.js"

  import {
    reLaunchToHome,
    navigateToPath,
  } from "@/assets/scripts/navigate.js"

  const loadingText = ref('登录中')
  const pageParams = ref('')

  const getUrlParam = (name) => {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
    const r = window.location.search.substr(1).match(reg)
    if (r != null) {
      return unescape(r[2])
    }
    return null
  }

  const getCode = () => {
    const code = getUrlParam('code')
    const local =
      `${baseUrl}/pages/others/login${location.href.includes('?')?'?'+location.href.slice(location.href.indexOf('?')+1,999):''}`
    if (code == null || code === "") {
      window.location.href =
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
      return
    } else {
      return code
    }
  }

  const getInfo_init = async () => {
    const res = await getInfoApi()
    if (res.code === 200) {
      // console.log(res.user);
      uni.setStorageSync('user', res.user)
    } else {
      uni.showToast({
        title: '获取用户信息失败',
        icon: 'error',
        complete: () => {
          loadingText.value = '获取用户信息失败'
        }
      })
    }
  }

  onMounted(() => {
    const route = useRoute()
    if (route.query.pageParams && route.query.pageParams !== 'undefined') {
      pageParams.value = route.query.pageParams.replace(/&/g, '(billkes)')
    }
    uni.removeStorageSync('token')
    const code = getCode()
    if (!code) return
    // sconsole.log(code);
    loginApi(code).then(async (res) => {
      if (res.code == 200) {
        const token = res.token
        uni.setStorageSync('token', token)
        await getInfo_init()
        if (pageParams.value) {
          navigateToPath(pageParams.value.replace(/\(billkes\)/g, '&'))
        } else {
          reLaunchToHome()
        }
      } else {
        uni.showToast({
          title: '登录失败',
          icon: 'error',
          complete: () => {
            loadingText.value = res.msg
          }
        })
      }
    })
  })
</script>

<template>
  <uv-loading-page :loading="true" loading-mode="semicircle" :loadingText='loadingText' color="#00A2E8"
    loadingColor="#00A2E8"></uv-loading-page>
</template>

<style lang="scss" scoped>
</style>